<?php
namespace Home\Controller;

use Utuo\ForegroundController;

/**
 * 微预约
 * @author song
 */
class SubscribeController extends ForegroundController {
	
	private $subscribe = null;
	
	public function _init() {
		$id = I('id', 0, "intval"); // 预约活动id
		if($id) {
			$d = D('My/Subscribe');
			$condition = array('end_time'=> array('exp',' > unix_timestamp(now())'),
					'start_time'=> array('exp',' <= unix_timestamp(now())'),
					'cid' => $this->sid,
					'status' => 1,
					'is_deleted' => 0,
					'id' => $id
			);
			$this->subscribe = $d->where($condition)->order('id desc')->find();
		}
	}
	
	public function showAction() {
		header('Content-Type:text/html; charset=utf-8');
		if(!$this->subscribe){
			exit('预约活动未开始');
		}elseif(empty($this->subscribe['items'])){
			exit('请设置提交字段');
		}
		$d = D('My/Subscribe');
		$this->assign("subscribe", $this->subscribe);
		$this->assign("items", $d->items);
		$this->assign("form", $d->createForm($this->subscribe['items']));
		$this->display();
	}
	
	public function resultAction() {
		$err = false;
		$vid = I('vid', 0, "intval"); //活动id
		$d = D('My/Subscribe');
		$subscribe = $d->where(array('id' => $vid, 'cid'=> $this->sid))->find();
		if($subscribe) {
			$m = D("SubscribeUser");
			$m->setupAutoAndValidate($subscribe['items']);
			if($dat = $m->create()) {
				$m->subscribe_id = $vid;
				$m->cid = $this->sid;
				false !== $m->add()?$this->ajaxReturn(array('state'=>1,'msg'=>$subscribe['result'])):$this->ajaxReturn(array(
					'state'=>0,
					'msg'=>'添加失败'	.$m->getError().$m->getLastSql().json_encode($dat)
				));
				
			}else{
				$this->ajaxReturn(array(
					'state'=>0,
					'msg'=>'创建数据失败'.$m->getError()
				));
			}
		} else {
			//$err or $err = '您选择的预约活动已不存在.';
			$this->ajaxReturn(array(
					'state'=>0,
					'msg'=>'您选择的预约活动已不存在'
			));
			
		}
		//$this->assign("error", $err);
		//$this->display();
	}

}